<template>
  <div class="work-display">
    <div class="section-header">
      <h3 class="section-title">
        <el-icon class="title-icon"><Grid /></el-icon>
        作品展示
      </h3>
      <div class="header-actions">
        <div class="view-controls">
          <el-radio-group v-model="viewMode" size="small">
            <el-radio-button value="grid">网格</el-radio-button>
            <el-radio-button value="list">列表</el-radio-button>
          </el-radio-group>
        </div>
        
      </div>
    </div>
    
    <!-- 统计信息 -->
    <div class="stats-bar" v-if="works.length > 0">
      <div class="stats-item">
        <span class="stats-label">总数：</span>
        <span class="stats-value">{{ works.length }}</span>
      </div>
      <div class="stats-item">
        <span class="stats-label">视频：</span>
        <span class="stats-value">{{ videoCount }}</span>
      </div>
      <div class="stats-item">
        <span class="stats-label">图文：</span>
        <span class="stats-value">{{ imageCount }}</span>
      </div>
    </div>
    
    <!-- 作品列表 -->
    <div class="works-container" v-loading="loading">
      <div v-if="works.length === 0 && !loading" class="empty-state">
        <el-empty description="暂无作品数据">
          <el-button type="primary" @click="handleRefresh" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新数据
          </el-button>
        </el-empty>
      </div>
      
      <div v-else :class="['works-list', viewMode]">
        <div
          v-for="work in displayWorks"
          :key="work.id"
          class="work-card"
        >
          <!-- 作品封面 -->
          <div class="work-cover">
            <div class="cover-image">
              <img :src="work.cover" :alt="work.title" @error="handleImageError" />
              <div class="cover-overlay">
                <div class="image-count" v-if="work.type === 'image' && work.imageCount > 1">
                  <el-icon><Picture /></el-icon>
                  {{ work.imageCount }}
                </div>
              </div>
            </div>
            <div class="work-type-badge" :class="work.type">
              {{ work.type === 'video' ? '视频' : '图文' }}
            </div>
          </div>
          
          <!-- 作品信息 -->
          <div class="work-info">
            <div class="work-title" :title="work.title">
              {{ work.title }}
            </div>
            
            <!-- 作者信息 -->
            <div class="author-info">
              <img :src="work.authorAvatar" :alt="work.authorName" class="author-avatar" />
              <span class="author-name">{{ work.authorName }}</span>
              <div class="author-badges">
                <el-tag v-if="work.authorVerified" size="small" type="success">认证</el-tag>
                <el-tag v-if="work.authorType === 'enterprise'" size="small" type="warning">企业</el-tag>
              </div>
            </div>
            
            <!-- 互动数据 -->
            <div class="interaction-data">
              <div class="data-item likes">
                <span class="emoji-icon">❤️</span>
                <span>{{ formatNumber(work.likes) }}</span>
              </div>
              <div class="data-item comments">
                <span class="emoji-icon">💬</span>
                <span>{{ formatNumber(work.comments) }}</span>
              </div>
              <div class="data-item shares">
                <span class="emoji-icon">🔗</span>
                <span>{{ formatNumber(work.shares) }}</span>
              </div>
              <div class="data-item collections">
                <span class="emoji-icon">⭐</span>
                <span>{{ formatNumber(work.collections || 0) }}</span>
              </div>
            </div>
            
            <!-- 标签 -->
            <div class="work-tags" v-if="work.tags && work.tags.length > 0">
              <el-tag
                v-for="tag in work.tags.slice(0, 3)"
                :key="tag"
                size="small"
                class="work-tag"
              >
                {{ tag }}
              </el-tag>
            </div>
            
            <!-- 发布时间 -->
            <div class="publish-time">
              {{ work.publishTime }}
            </div>
            
            <!-- 操作按钮 -->
            <div class="work-actions">
              <el-button 
                size="small" 
                type="primary" 
                @click="handleWorkAnalysis(work)"
              >
                内容分析
              </el-button>
              <el-button 
                size="small" 
                type="default" 
                @click="handleViewOriginal(work)"
              >
                查看原贴
              </el-button>
            </div>
          </div>
          
        </div>
      </div>
    </div>
    
    <!-- 分页 -->
    <div class="pagination-container" v-if="works.length > pageSize">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[12, 24, 48, 96]"
        :total="works.length"
        layout="total, sizes, prev, pager, next, jumper"
        background
      />
    </div>
    
    <!-- 筛选对话框 -->
    <el-dialog
      v-model="showFilterDialog"
      title="筛选条件"
      width="500px"
      :before-close="handleFilterClose"
    >
      <div class="filter-form">
        <div class="filter-group">
          <label>内容类型：</label>
          <el-checkbox-group v-model="filterForm.contentType">
            <el-checkbox value="video">视频</el-checkbox>
            <el-checkbox value="image">图文</el-checkbox>
          </el-checkbox-group>
        </div>
        
        <div class="filter-group">
          <label>点赞数范围：</label>
          <div class="range-inputs">
            <el-input v-model="filterForm.likesMin" placeholder="最小值" type="number" />
            <span>-</span>
            <el-input v-model="filterForm.likesMax" placeholder="最大值" type="number" />
          </div>
        </div>
        
        <div class="filter-group">
          <label>评论数范围：</label>
          <div class="range-inputs">
            <el-input v-model="filterForm.commentsMin" placeholder="最小值" type="number" />
            <span>-</span>
            <el-input v-model="filterForm.commentsMax" placeholder="最大值" type="number" />
          </div>
        </div>
        
        <div class="filter-group">
          <label>发布时间：</label>
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetFilter">重置</el-button>
          <el-button @click="showFilterDialog = false">取消</el-button>
          <el-button type="primary" @click="applyFilter">应用</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
/** @name 作品展示组件 */
import { 
  Grid, 
  Refresh,
  VideoPlay,
  Picture
} from "@element-plus/icons-vue"
import { listAPI } from '@/request/apis/main.js'


// Props
const props = defineProps({
  // 移除 works 和 loading props，改为内部管理
})

// Emits
const emit = defineEmits(['work-click', 'work-analysis', 'analyze', 'download'])

// 响应式数据
const viewMode = ref('grid')
const sortBy = ref('default')
const currentPage = ref(1)
const pageSize = ref(24)
const showFilterDialog = ref(false)
const loading = ref(false)
const works = ref([])

// 筛选表单
const filterForm = ref({
  contentType: ['video', 'image'],
  likesMin: '',
  likesMax: '',
  commentsMin: '',
  commentsMax: '',
  dateRange: []
})

// 计算属性
const videoCount = computed(() => {
  return works.value.filter(work => work.type === 'video').length
})

const imageCount = computed(() => {
  return works.value.filter(work => work.type === 'image').length
})

const totalLikes = computed(() => {
  return works.value.reduce((sum, work) => sum + work.likes, 0)
})

const totalComments = computed(() => {
  return works.value.reduce((sum, work) => sum + work.comments, 0)
})

const filteredWorks = computed(() => {
  let filtered = [...works.value]
  
  // 内容类型筛选
  if (filterForm.value.contentType.length > 0) {
    filtered = filtered.filter(work => filterForm.value.contentType.includes(work.type))
  }
  
  // 点赞数筛选
  if (filterForm.value.likesMin) {
    filtered = filtered.filter(work => work.likes >= parseInt(filterForm.value.likesMin))
  }
  if (filterForm.value.likesMax) {
    filtered = filtered.filter(work => work.likes <= parseInt(filterForm.value.likesMax))
  }
  
  // 评论数筛选
  if (filterForm.value.commentsMin) {
    filtered = filtered.filter(work => work.comments >= parseInt(filterForm.value.commentsMin))
  }
  if (filterForm.value.commentsMax) {
    filtered = filtered.filter(work => work.comments <= parseInt(filterForm.value.commentsMax))
  }
  
  // 日期筛选
  if (filterForm.value.dateRange && filterForm.value.dateRange.length === 2) {
    const [startDate, endDate] = filterForm.value.dateRange
    filtered = filtered.filter(work => {
      const publishDate = new Date(work.publishTime)
      return publishDate >= new Date(startDate) && publishDate <= new Date(endDate)
    })
  }
  
  return filtered
})

const sortedWorks = computed(() => {
  const works = [...filteredWorks.value]
  
  switch (sortBy.value) {
    case 'latest':
      return works.sort((a, b) => new Date(b.publishTime) - new Date(a.publishTime))
    case 'likes':
      return works.sort((a, b) => b.likes - a.likes)
    case 'comments':
      return works.sort((a, b) => b.comments - a.comments)
    case 'shares':
      return works.sort((a, b) => b.shares - a.shares)
    default:
      return works
  }
})

const displayWorks = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return sortedWorks.value.slice(start, end)
})

/** @name 数据映射函数 - 将接口数据转换为组件所需格式 */
function mapApiDataToWorkFormat(apiData) {
  return {
    id: apiData.id,
    title: apiData.title,
    cover: apiData.cover,
    type: apiData.type, // 'video' 或 'image'
    likes: apiData.like_count,
    comments: apiData.comment_count,
    shares: apiData.share_count,
    collections: apiData.collect_count,
    authorName: apiData.kol_name,
    authorAvatar: apiData.kol_avatar || 'https://picsum.photos/40/40?random=avatar',
    authorVerified: false, // 接口中没有此字段，默认为 false
    authorType: 'normal', // 接口中没有此字段，默认为 normal
    tags: apiData.tags ? apiData.tags.split(',').map(tag => tag.trim()) : [],
    publishTime: apiData.release_time,
    imageCount: 1, // 接口中没有此字段，默认为 1
    url: apiData.source_link
  }
}

/** @name 获取作品列表数据 */
async function fetchWorksList() {
  try {
    loading.value = true
    const response = await listAPI()
    
    if (response.code === 0 && response.data && response.data.list) {
      // 将接口数据映射为组件所需格式
      works.value = response.data.list.map(mapApiDataToWorkFormat)
    } else {
      ElMessage.error('获取数据失败：' + (response.msg || '未知错误'))
      works.value = []
    }
  } catch (error) {
    console.error('获取作品列表失败:', error)
    ElMessage.error('网络请求失败，请稍后重试')
    works.value = []
  } finally {
    loading.value = false
  }
}

/** @name 格式化数字 */
function formatNumber(num) {
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + 'w'
  }
  if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'k'
  }
  return num.toString()
}

/** @name 处理图片加载错误 */
function handleImageError(event) {
  event.target.src = 'https://picsum.photos/300/400?random=error'
}

/** @name 处理作品点击 */
function handleWorkClick(work) {
  emit('work-click', work)
}

/** @name 处理查看原贴 */
function handleViewOriginal(work) {
  if (work.url) {
    window.open(work.url, '_blank')
  } else {
    ElMessage.warning('暂无原贴链接')
  }
}

/** @name 处理分析 */
function handleAnalyze(work) {
  emit('analyze', work)
}

/** @name 处理作品分析 */
function handleWorkAnalysis(work) {
  emit('work-analysis', work)
}

/** @name 处理下载 */
function handleDownload(work) {
  emit('download', work)
}

/** @name 处理更多操作 */
function handleMoreAction({ action, work }) {
  switch (action) {
    case 'copy':
      navigator.clipboard.writeText(work.url || `https://douyin.com/video/${work.id}`)
      ElMessage.success('链接已复制到剪贴板')
      break
    case 'export':
      exportWorkData(work)
      break
    case 'favorite':
      ElMessage.success('已添加到收藏')
      break
    case 'report':
      ElMessage.info('举报功能开发中')
      break
  }
}

/** @name 导出作品数据 */
function exportWorkData(work) {
  const data = {
    id: work.id,
    title: work.title,
    author: work.authorName,
    likes: work.likes,
    comments: work.comments,
    shares: work.shares,
    publishTime: work.publishTime,
    tags: work.tags
  }
  
  const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `work-${work.id}.json`
  a.click()
  URL.revokeObjectURL(url)
  
  ElMessage.success('数据导出成功')
}

/** @name 重置筛选 */
function resetFilter() {
  filterForm.value = {
    contentType: ['video', 'image'],
    likesMin: '',
    likesMax: '',
    commentsMin: '',
    commentsMax: '',
    dateRange: []
  }
}

/** @name 应用筛选 */
function applyFilter() {
  showFilterDialog.value = false
  currentPage.value = 1
  ElMessage.success('筛选条件已应用')
}

/** @name 处理筛选对话框关闭 */
function handleFilterClose() {
  showFilterDialog.value = false
}

/** @name 刷新数据 */
function handleRefresh() {
  console.log('刷新数据')
  fetchWorksList()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchWorksList()
})

// 监听排序变化
watch(sortBy, () => {
  currentPage.value = 1
})

// 监听筛选变化
watch(filterForm, () => {
  currentPage.value = 1
}, { deep: true })


defineExpose({
  handleRefresh
})
</script>

<style lang="scss" scoped>
.work-display {
  background: $qf-color-bg2;
  border: 1px solid $qf-border-color;
  border-radius: $qf-border-radius-lg;
  padding: 20px;
  
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    
    .section-title {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 18px;
      font-weight: 600;
      color: $qf-text-color-primary;
      margin: 0;
      
      .title-icon {
        color: $qf-primary;
      }
    }
    
    .header-actions {
      display: flex;
      align-items: center;
      gap: 12px;
    }
  }
  
  .stats-bar {
    display: flex;
    gap: 24px;
    padding: 12px 16px;
    background: $qf-color-bg3;
    border: 1px solid $qf-border-color;
    border-radius: $qf-border-radius-base;
    margin-bottom: 16px;
    
    .stats-item {
      display: flex;
      align-items: center;
      gap: 4px;
      
      .stats-label {
        font-size: 13px;
        color: $qf-text-color-secondary;
      }
      
      .stats-value {
        font-size: 14px;
        font-weight: 500;
        color: $qf-text-color-primary;
      }
    }
  }
  
  .works-container {
    min-height: 400px;
    
    .empty-state {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 400px;
    }
    
    .works-list {
      &.grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
        gap: 16px;
      }
      
      &.list {
        display: flex;
        flex-direction: column;
        gap: 12px;
        
        .work-card {
          display: flex;
          align-items: center;
          padding: 12px;
          
          .work-cover {
            width: 120px;
            height: 80px;
            flex-shrink: 0;
            margin-right: 12px;
          }
          
          .work-info {
            flex: 1;
            
            .work-title {
              font-size: 16px;
              margin-bottom: 8px;
            }
            
            .author-info,
            .interaction-data,
            .work-tags,
            .publish-time {
              margin-bottom: 4px;
            }
          }
          
          .work-actions {
            flex-shrink: 0;
          }
        }
      }
    }
    
    .work-card {
      background: $qf-color-bg3;
      border: 1px solid $qf-border-color;
      border-radius: $qf-border-radius-base;
      padding: 12px;
      cursor: pointer;
      transition: all 0.2s ease;
      position: relative;
      
      &:hover {
        border-color: $qf-primary;
        box-shadow: 0 4px 12px rgba(151, 164, 255, 0.15);
        transform: translateY(-2px);
      }
      
      .work-cover {
        position: relative;
        width: 100%;
        height: 180px;
        margin-bottom: 12px;
        border-radius: $qf-border-radius-base;
        overflow: hidden;
        
        .cover-image {
          position: relative;
          width: 100%;
          height: 100%;
          
          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
          
          .cover-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.3);
            display: flex;
            align-items: center;
            justify-content: center;
            opacity: 0;
            transition: opacity 0.2s ease;
            
            .play-icon {
              color: white;
              background: rgba(0, 0, 0, 0.6);
              border-radius: 50%;
              width: 48px;
              height: 48px;
              display: flex;
              align-items: center;
              justify-content: center;
            }
            
            .image-count {
              position: absolute;
              top: 8px;
              right: 8px;
              background: rgba(0, 0, 0, 0.7);
              color: white;
              padding: 4px 8px;
              border-radius: $qf-border-radius-sm;
              font-size: 12px;
              display: flex;
              align-items: center;
              gap: 4px;
            }
          }
          
          &:hover .cover-overlay {
            opacity: 1;
          }
        }
        
        .work-type-badge {
          position: absolute;
          top: 8px;
          left: 8px;
          padding: 2px 6px;
          border-radius: $qf-border-radius-sm;
          font-size: 12px;
          font-weight: 500;
          
          &.video {
            background: $qf-primary;
            color: white;
          }
          
          &.image {
            background: $qf-color-success;
            color: white;
          }
        }
      }
      
      .work-info {
        .work-title {
          font-size: 14px;
          font-weight: 500;
          color: $qf-text-color-primary;
          margin-bottom: 8px;
          line-height: 1.4;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }
        
        .author-info {
          display: flex;
          align-items: center;
          gap: 6px;
          margin-bottom: 8px;
          
          .author-avatar {
            width: 20px;
            height: 20px;
            border-radius: 50%;
            object-fit: cover;
          }
          
          .author-name {
            font-size: 12px;
            color: $qf-text-color-secondary;
            flex: 1;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          
          .author-badges {
            display: flex;
            gap: 4px;
          }
        }
        
        .interaction-data {
          display: flex;
          gap: 12px;
          margin-bottom: 8px;
          
          .data-item {
            display: flex;
            align-items: center;
            gap: 4px;
            font-size: 12px;
            color: $qf-text-color-secondary;
            
            .el-icon {
              font-size: 14px;
            }
            
            &.likes .el-icon {
              color: #ff6b6b;
            }
            
            &.comments .el-icon {
              color: #4ecdc4;
            }
            
            &.shares .el-icon {
              color: #45b7d1;
            }
          }
        }
        
        .work-tags {
          display: flex;
          gap: 4px;
          margin-bottom: 8px;
          flex-wrap: wrap;
          
          .work-tag {
            font-size: 11px;
            height: 20px;
            line-height: 18px;
            padding: 0 6px;
          }
        }
        
        .publish-time {
          font-size: 11px;
          color: $qf-text-color-disabled;
        }
        
        .work-actions {
          display: flex;
          gap: 8px;
          margin-top: 12px;
          
          .el-button {
            flex: 1;
            min-width: 0;
          }
        }
      }
      
      .work-actions {
        position: absolute;
        top: 8px;
        right: 8px;
        display: flex;
        gap: 4px;
        opacity: 0;
        transition: opacity 0.2s ease;
        
        .el-button {
          background: rgba(0, 0, 0, 0.7);
          color: white;
          border: none;
          
          &:hover {
            background: rgba(0, 0, 0, 0.9);
          }
        }
      }
      
      &:hover .work-actions {
        opacity: 1;
      }
    }
  }
  
  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 24px;
  }
  
  .filter-form {
    .filter-group {
      display: flex;
      align-items: center;
      margin-bottom: 16px;
      
      label {
        width: 100px;
        font-size: 14px;
        color: $qf-text-color-secondary;
        flex-shrink: 0;
      }
      
      .range-inputs {
        display: flex;
        align-items: center;
        gap: 8px;
        
        .el-input {
          width: 100px;
        }
        
        span {
          color: $qf-text-color-secondary;
        }
      }
      
      .el-checkbox-group {
        display: flex;
        gap: 12px;
      }
    }
  }
}
</style>